﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace XQ.Extension
{
    /// <summary>
    /// 序列化
    /// </summary>
    public static class SerializeHelper
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static string Base64Serializable(this object target)
        {
            return _Base64Serializable(target);
        }

        /// <summary>
        /// 序列化方法
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static string _Base64Serializable(object target)
        {
            using (var stream = new MemoryStream())
            {
                new BinaryFormatter().Serialize(stream, target);
                return Convert.ToBase64String(stream.ToArray());
            }
        }



        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <returns></returns>
        public static T Base64Derializable<T>(this string target)
        {
            return _Base64Derializable<T>(target);
        }


        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <returns></returns>
        public static T _Base64Derializable<T>(this string target)
        {
            byte[] targetArray = Convert.FromBase64String(target);
            using (var stream = new MemoryStream(targetArray))
            {
                return (T)(new BinaryFormatter().Deserialize(stream));
            }
        }





        /// <summary>
        /// 合并反序列化与序列化(用户对象拷贝 设计模式中)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T DeepClone<T>(T t)
        {
            return t.Base64Serializable().Base64Derializable<T>();
        }
    }
}
